/**
 * 测试Java的反射机制
 * @author MIAO
 * Created on 2011-10-27
 * For more information, please visit:ismiao.com
 */
package com.ismiao.example.Reflection;

import java.awt.Button;
import java.lang.reflect.Method;
import java.util.Hashtable;

public class ReflectionTest {
	/**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        ReflectionTest reflection = new ReflectionTest();
        reflection.getNameTest();
        System.out.println("");
        reflection.getMethodTest();
    }
    
    /**
     * Class的getName()方法测试
     * @throws Exception
     */
    public void getNameTest() throws Exception {
        System.out.println("===========begin getNameTest============");
        String name = "amigo";
        Class<? extends String> cls = name.getClass();
        System.out.println("string class name: " + cls.getName());
        
        Button btn = new Button();
        Class<? extends Button> btnClass = btn.getClass();
        System.out.println("button class name: " + btnClass.getName());
        Class superBtnClass = btnClass.getSuperclass();
        System.out.println("super button class name: " + superBtnClass.getName());
        
        Class clsTest = Class.forName("java.awt.Button");
        System.out.println("clsTest name: " + clsTest.getName());
        System.out.println("===========end getNameTest============");
    }
    
    /**
     * Class的getMethod()方法测试
     * @throws Exception
     */
    public void getMethodTest() throws Exception {
        System.out.println("===========begin getMethodTest==========");
        Class<?> cls = Class.forName("com.ismiao.example.Reflection.ReflectionTest");
        Class<?> ptypes[] = new Class[2];
        ptypes[0] = Class.forName("java.lang.String");
        ptypes[1] = Class.forName("java.util.Hashtable");
        Method method = cls.getMethod("testMethod", ptypes);
        Object args[] = new Object[2];
        args[0] = "hello, my dear!";
        
        Hashtable<String, String> ht = new Hashtable<String, String>();
        ht.put("name", "amigo");
        args[1] = ht;
        
        String returnStr = (String) method.invoke(new ReflectionTest(), args);
        System.out.println("returnStr= " + returnStr);
        System.out.println("===========end getMethodTest==========");
    }

    public String testMethod(String str, Hashtable ht) throws Exception {
        String returnStr = "return str";
        System.out.println("begin testMethod invoked");
        System.out.println("str= " + str);
        System.out.println("name= " + (String) ht.get("name"));
        System.out.println("end testMethod invoked");
        return returnStr;
    }
}
